import time
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger


class ScheduledTask:
    def __init__(self, task):
        pass

    @staticmethod
    def execute(method, hours, method_id):
        scheduler = BackgroundScheduler()
        # 修改为每 3 小时触发一次
        intervalTrigger = IntervalTrigger(hours=hours)
        scheduler.add_job(method, intervalTrigger, id=method_id)
        scheduler.start()
        print(f'=== {method} ===')

        try:
            # 保持主线程运行，否则调度器会退出
            while True:
                time.sleep(1)
        except (KeyboardInterrupt, SystemExit):
            # 优雅地关闭调度器
            scheduler.shutdown()